#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <inttypes.h>
#include "realtime.h"

int main(int argc, char *argv[])
{
    struct timespec t, t1, t2;
    uint64_t interval = 50000; // 50000ns = 50us
    uint64_t count_one = 0;
    uint64_t count_zero = 0;
    uint64_t ns1, ns2;
    unsigned char value = 0;
    init_realtime();
    if(argc > 1)
        interval = atoi(argv[1]); 
    printf("interval=%lu\n", interval);
    //! Get current time
    clock_gettime(0, &t);
    //t.tv_sec++;
    clock_gettime(0, &t1);
    while(1)
    {
        //! Wait until next shot.
        clock_nanosleep(0, TIMER_ABSTIME, &t, NULL);
        if(value)
        {
            count_one ++;
        }else{
            count_zero ++;
        }
        value = ! value;
        //! Calculate next shot.
        #if 1
        t.tv_nsec += interval;
        tsnorm(&t);
        #else
        t.tv_nsec = interval;
        t.tv_sec = 0;
        nanosleep(&t, NULL);
        #endif
        clock_gettime(0, &t2);
        if(t2.tv_sec - t1.tv_sec > 5)
            break;
    }
    printf("one= %lu, zero= %lu\n", count_one, count_zero);
    ns1 = (t2.tv_sec*NSEC_PER_SEC + t2.tv_nsec) - 
                (t1.tv_sec*NSEC_PER_SEC + t1.tv_nsec);
    ns2 = count_one*interval + count_zero*interval;
    printf("ns1=%lu, ns2=%lu: %lu\n", ns1, ns2, ns1 - ns2);
    return 0;
}
